package com.mayuan.controller;

import com.mayuan.domain.ResponseResult;
import com.mayuan.domain.dto.MenuDto;
import com.mayuan.domain.entity.Menu;
import com.mayuan.domain.vo.MenuListVo;
import com.mayuan.domain.vo.MenuTreeVo;
import com.mayuan.domain.vo.RoleMenuTreeSelectVo;
import com.mayuan.service.MenuService;
import com.mayuan.utils.SystemConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/system/menu")
public class MenuController {

    @Autowired
    private MenuService menuService;

    @GetMapping("/list")
    public ResponseResult<MenuListVo> list(MenuDto menuDto){
        return menuService.list(menuDto);
    }

    @PostMapping
    public ResponseResult add(@RequestBody Menu menu){
        return menuService.add(menu);
    }

    @GetMapping("/{id}")
    public ResponseResult selectMenuInfo(@PathVariable("id") Long id){
        //根据id查询菜单数据
        return menuService.selectMenuInfo(id);
    }

    @PutMapping
    public ResponseResult updateMenu(@RequestBody Menu menu){
        //更新菜单
        return menuService.updateMenu(menu);
    }

    @DeleteMapping("/{menuId}")
    public ResponseResult deleteById(@PathVariable("menuId") Long menuId){
        return menuService.deleteById(menuId);
    }

    /**
     * 获取菜单下拉树列表
     */
    @GetMapping("/treeselect")
    public ResponseResult treeselect(){
        //复用之前的selectMenuList方法。方法需要参数，参数可以用来进行条件查询，而这个方法不需要条件，所以直接new Menu()传入
        List<Menu> menus = menuService.selectMenuList(new Menu());
        List<MenuTreeVo> options =  SystemConverter.buildMenuSelectTree(menus);
        return ResponseResult.okResult(options);
    }

    /**
     * 加载对应角色菜单列表树
     */
    @GetMapping(value = "/roleMenuTreeselect/{roleId}")
    public ResponseResult roleMenuTreeSelect(@PathVariable("roleId") Long roleId) {
        List<Menu> menus = menuService.selectMenuList(new Menu());
        List<Long> checkedKeys = menuService.selectMenuListByRoleId(roleId);
        List<MenuTreeVo> menuTreeVos = SystemConverter.buildMenuSelectTree(menus);
        RoleMenuTreeSelectVo vo = new RoleMenuTreeSelectVo(checkedKeys,menuTreeVos);
        return ResponseResult.okResult(vo);
    }
}
